package com.example.newinfinity

import android.animation.Animator
import android.os.Bundle
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.activityViewModels
import androidx.lifecycle.lifecycleScope
import androidx.navigation.fragment.findNavController
import com.example.newinfinity.MyViewModel.UserViewModel
import com.example.newinfinity.databinding.FragmentLottieAnimBinding
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext

class LottieAnimFragment : BaseFragment<FragmentLottieAnimBinding>() {
    private val userViewModel: UserViewModel by activityViewModels()

    override fun initViewBinding(): FragmentLottieAnimBinding {
        return FragmentLottieAnimBinding.inflate(layoutInflater)
    }

    //在该方法中可编写onCreateView时期需要编写的内容
    override fun initView() {
        super.initView()
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        mBinding.lottieAnim.addAnimatorListener(object : Animator.AnimatorListener {
            override fun onAnimationStart(animation: Animator) {}
            override fun onAnimationCancel(animation: Animator) {}
            override fun onAnimationRepeat(animation: Animator) {}
            override fun onAnimationEnd(animation: Animator) {
                //lottie动画结束 跳转到登录界面
                navigateNextFragment()
            }
        })
    }

    fun navigateNextFragment() {
        //假如已近有登录用户了 就直接跳转到主界面 跳过登陆注册界面
        lifecycleScope.launch {
            val currentCheckInUser = userViewModel.getCurrentLoginInUser()
            if (currentCheckInUser != null) {
                //有登录用户了 跳转主界面
                withContext(Dispatchers.Main) {
                    findNavController().navigate(R.id.action_lottieAnimFragment_to_homeFragment)
                }
            } else {
                //没有登录用户 跳转登录界面
                withContext(Dispatchers.Main) {
                    findNavController().navigate(R.id.action_lottieAnimFragment_to_loginFragment)
                }
            }
        }
    }

}